package pt.compflow.client.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.restlet.data.Status;
import org.restlet.representation.EmptyRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.Get;

import pt.compflow.Context;
import pt.compflow.flowontology.model.FLOWO;
import pt.compflow.flowontology.model.FlowOntologyModel;
import pt.compflow.flowontology.model.Interface;
import pt.compflow.flowontology.model.Person;
import pt.compflow.storage.TripleStoreConnection;

import com.hp.hpl.jena.ontology.OntClass;

public class InterfaceUIResource extends UIBaseResource {

//	private static final Logger LOG = LoggerFactory.getLogger(PersonResource.class);
	
	@Get
	public Representation get() {
		Context context = getCompFlowContext();
		TripleStoreConnection store = context.getStoreConnection();
		store.openStore();
		
		FlowOntologyModel model = store.connectModel();
		
		Person p = getPerson(model, null);
		if(p == null) {
			redirectSeeOther("/_login");
			store.closeStore();
			return new EmptyRepresentation();
		}
		if(!isAdmin(p)) {
			setStatus(Status.CLIENT_ERROR_UNAUTHORIZED);
			store.closeStore();
			return new EmptyRepresentation();
		}
		
		Map<String, Object> argumentMap = new HashMap<String, Object>();
		argumentMap.put("person", getPersonMap(model, p, true));
		argumentMap.put("taskInterfaces", getInterfaces(context, model, FLOWO.TaskInterface));
		argumentMap.put("eventInterfaces", getInterfaces(context, model, FLOWO.EventInterface));
		
		store.closeStore();
		
		return getTemplateRepresentation("InterfaceTemplate.ftl", argumentMap);
	}
	
	private List<Map<String, Object>> getInterfaces(Context context, FlowOntologyModel model, OntClass c) {
		
		List<Map<String, Object>> result = new ArrayList<Map<String,Object>>();
		
		Iterator<? extends Interface> it = c.equals(FLOWO.TaskInterface) ? model.listTaskInterfaces() : model.listEventInterfaces();
		
		while(it.hasNext()) {
			Interface i = it.next();
			
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("uri", i.getURI());
			map.put("shortUri", i.getLocalName());
			map.put("label", i.getLabel(null));
			map.put("description", i.getDescription(null));
			result.add(map);
			
		}
		
		return result;
		
	}
	
	
}
